# coding:utf-8
'''
   Author:段超恒
   Time: 18/3/11
   Email:296008606@qq.cm
'''


'''
1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
 第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时
'''
import time

def a10_times(func):
    def times():
        time1=time.time()
        func()
        time2=time.time()
        print("消耗的时间为：%s"%(time2-time1))
    return times
# 普通方式
@a10_times
def b10_sum():
    for i in range(10):
        sum(range(1,999999))

def b1_sum():
    sum(range(1,999999))


# 多线程
from threading import Thread
@a10_times
def b10_thread():
    list=[Thread(target=b1_sum, args=())for num in range(10)]
    for i in list:
        i.start()
        i.join()
# 多进程
from multiprocessing import Process
@a10_times
def b10_process():
    list=[Process(target=b1_sum, args=())for num in range(10)]
    for i in list:
        i.start()
        i.join()



'''
2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定
'''
def c10_times(func):
    def times():
        time1=time.time()
        func()
        time2=time.time()
        print("消耗的时间为：%s"%(time2-time1))
    return times
# 普通方式
@c10_times
def c10_sum():
    for i in range(10):
        sum(range(1,999999))
# 线程
def c1_sum():
    sum(range(1,999999))

from multiprocessing.dummy import Pool as threadpool #线程对象
# 开启10个子线程池
@c10_times
def c10_threadpool():
    pool = threadpool(cpu_count())
    for num in range(10):
        pool.apply_async(c1_sum, args=())  # 异步
    pool.close()  # 关闭进程池
    pool.join()  # 主进程等待进程池进程完成
# 进程池
from multiprocessing import Pool ,cpu_count#进程对象
@c10_times
def c10_pool():
    pool=Pool(cpu_count())
    for i in range(10):
        pool.apply_async(c1_sum,args=())
    pool.close()#关闭进程池，不接收新的进程
    pool.join()

if __name__=="__main__":
    # b10_sum()
     b10_thread()
    # b10_process()
    #c10_sum()
    #c10_threadpool()
    #c10_pool()